package fr.gaulupeau.apps.Poche.tts.utils;

import android.content.Context;
import android.content.res.Resources;
import android.os.Build;
import android.text.Html;
import android.text.TextUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class TextTools {

    /**
     * Returns true if both arguments are equal or empty.
     * {@code null} and empty sequences are considered equal.
     *
     * @param s1 first char sequence
     * @param s2 second char sequence
     * @return true if arguments are considered equal
     */
    public static boolean equalOrEmpty(CharSequence s1, CharSequence s2) {
        return (TextUtils.isEmpty(s1) && TextUtils.isEmpty(s2))
                || TextUtils.equals(s1, s2);
    }

    public static String unescapeHtml(String s) {
        if (s == null) return null;

        return Html.fromHtml(s, Html.FROM_HTML_MODE_LEGACY).toString();
    }

    public static String readRawString(Context context, int id) {
        try {
            return readRawStringUnsafe(context,id);
        } catch (IOException e) {
            throw new RuntimeException("Couldn't load raw resource", e);
        }
    }

    public static String readRawStringUnsafe(Context context,int id) throws IOException {
        Resources resources = context.getResources();

        try (BufferedReader reader = new BufferedReader(
                new InputStreamReader(resources.openRawResource(id)))) {

            StringBuilder sb = new StringBuilder();
            String s;
            while ((s = reader.readLine()) != null) {
                sb.append(s).append('\n');
            }

            return sb.toString();
        }
    }
}
